using AvalonAdmin.Attributes;
using AvalonAdmin.BaseViewModel;
using AvalonAdmin.Consts;
using AvalonAdmin.Helpers;
using AvalonAdmin.Pages.Rule.Views.RuleConfig;
using AvalonAdminDto.Common;
using AvalonAdminDto.Rule.RuleConfigDtos;
using D.UtilCore.Dtos;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Ursa.Controls;

namespace AvalonAdmin.Pages.Rule.ViewModels.RuleConfig
{
    /// <summary>
    /// 规则配置查询视图模型
    /// </summary>
    [PagePath("Rule.Views.RuleConfig.Page_RuleConfig_Query")]
    public class RuleConfigQueryViewModel : SimpleIntegratedViewModel<RepRuleConfig>
    {


        #region 查询条件
        private string? _name;
        /// <summary>
        /// 名称
        /// </summary>
        public string? Name
        {
            get => _name;
            set => SetProperty(ref _name, value);
        }
        #endregion

        #region 构造函数
        private RepRuleConfig? _selectedRuleConfig;

        /// <summary>
        /// 初始化规则配置查询视图模型
        /// </summary>
        public RuleConfigQueryViewModel()
        {
            _ = Task.Run(async () => await QueryAsync());
        }
        #endregion

        #region 重写基类方法
        /// <summary>
        /// 重置查询条件
        /// </summary>
        public void ResetQuery()
        {
            Name = string.Empty;
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        public override async Task QueryAsync()
        {
            await ExecuteWithLoadingAsync(async () =>
            {
                var queryModel = new RepRuleConfig
                {
                    Name = Name
                };

                var response = await HttpHelper<List<RepRuleConfig>>.PostAsync(ApiUrl.QueryRuleConfigList, queryModel);
                
                if (response.Code == StatusCodeEnum.OK && response.Data != null)
                {
                    Data.Clear();
                    foreach (var item in response.Data)
                    {
                        item.IsSelected = false;
                        Data.Add(item);
                    }
                }
                else
                {
                    await MessageBox.ShowAsync($"查询失败: {response.Msg}");
                }
            });
        }

        /// <summary>
        /// 添加规则配置
        /// </summary>
        public override async Task AddAsync(RepRuleConfig? obj = default)
        {
            var viewModel = new RuleConfigModifyViewModel(string.Empty);
            var result = await Dialog.ShowModal<Page_RuleConfig_Modify, RuleConfigModifyViewModel>(viewModel);
            
            if (result == true)
            {
                await QueryAsync();
            }
        }

        /// <summary>
        /// 更新规则配置
        /// </summary>
        public override async Task UpdateAsync(RepRuleConfig? obj = default)
        {
            var target = obj ?? SelectedModel;
            if (target?.Id == null)
            {
                await MessageBox.ShowAsync("请选择要修改的规则配置");
                return;
            }

            var viewModel = new RuleConfigModifyViewModel(target.Id);
            var result = await Dialog.ShowModal<Page_RuleConfig_Modify, RuleConfigModifyViewModel>(viewModel);
            
            if (result == true)
            {
                await QueryAsync();
            }
        }

        /// <summary>
        /// 删除规则配置
        /// </summary>
        public override async Task DeleteAsync(RepRuleConfig? obj = default)
        {
            var target = obj ?? SelectedModel;
            if (target?.Id == null)
            {
                await MessageBox.ShowAsync("请选择要删除的规则配置");
                return;
            }

            var result = await MessageBox.ShowAsync($"确定要删除规则配置 '{target.Name}' 吗？", "确认删除", MessageBoxButton.YesNo);
            if (result == MessageBoxResult.Yes)
            {
                await ExecuteWithLoadingAsync(async () =>
                {
                    var response = await HttpHelper<bool>.PostAsync(ApiUrl.DeleteRuleConfig, new { id = target.Id });
                    
                    if (response.Code == StatusCodeEnum.OK)
                    {
                        await MessageBox.ShowAsync("删除成功");
                        await QueryAsync();
                    }
                    else
                    {
                        await MessageBox.ShowAsync($"删除失败: {response.Msg}");
                    }
                });
            }
        }

        /// <summary>
        /// 批量删除规则配置
        /// </summary>
        public override async Task BatchDeleteAsync(IEnumerable<RepRuleConfig>? items = null)
        {
            var selectedItems = Data?.Where(x => x.IsSelected).ToList();
            if (selectedItems == null || !selectedItems.Any())
            {
                await MessageBox.ShowAsync("请选择要删除的项目");
                return;
            }

            var result = await MessageBox.ShowAsync($"确定要删除选中的 {selectedItems.Count} 个规则配置吗？", "确认删除", MessageBoxButton.YesNo);
            if (result == MessageBoxResult.Yes)
            {
                await ExecuteWithLoadingAsync(async () =>
                {
                    var ids = selectedItems.Select(x => x.Id).ToList();
                    var response = await HttpHelper<bool>.PostAsync(ApiUrl.BatchDeleteRuleConfig, new { ids });
                    
                    if (response.Code == StatusCodeEnum.OK)
                    {
                        await MessageBox.ShowAsync("批量删除成功");
                        await QueryAsync();
                    }
                    else
                    {
                        await MessageBox.ShowAsync($"批量删除失败: {response.Msg}");
                    }
                });
            }
        }

        /// <summary>
        /// 获取项目选中状态
        /// </summary>
        protected override bool GetIsSelected(RepRuleConfig item)
        {
            return item.IsSelected;
        }

        /// <summary>
        /// 设置项目选中状态
        /// </summary>
        protected override void SetIsSelected(RepRuleConfig item, bool isSelected)
        {
            item.IsSelected = isSelected;
        }
        #endregion



        #region 业务方法
        /// <summary>
        /// 信息请求事件
        /// </summary>
        public event AvalonAdmin.BaseViewModel.InformationRequestedHandler? InformationRequested;
        
        /// <summary>
        /// 提交选中的规则配置
        /// </summary>
        public async Task SubmitAsync()
        {
            var selectedItems = Data?.Where(x => x.IsSelected).ToList();
            
            if (selectedItems == null || !selectedItems.Any())
            {
                await MessageBox.ShowAsync("请选择一个规则配置");
                return;
            }
            
            if (selectedItems.Count > 1)
            {
                await MessageBox.ShowAsync("只能选择一个规则配置");
                return;
            }

            _selectedRuleConfig = selectedItems.First();
            InformationRequested?.Invoke(this, new InformationEventArgs<RepRuleConfig>(_selectedRuleConfig));
        }
        #endregion


    }
}


